import storage from '@/util/storage';

let ws = {
    _ws: null,
    _timeout: 50 * 1000,
    _callbacks: {},
    _params: {},
    is_connected: false,
    _connect_param: {api: 'heartbeat'},
    initWs: function() {
        console.log('socketjs init');
        let self = this;
        this.is_connected = false;
        this._ws = null;
        const ws_base = 'ws://api.huojisuan.com:2346/unit';
        const a_token = storage.local.get('a_token');
        const u_token = storage.local.get('u_token');
        console.log(a_token)
        this._ws = new WebSocket( `${ws_base}?a=${a_token}&u=${u_token}`);
        this._ws.onopen = this.wsOpen;
        this._ws.onmessage = this.wsMsg;
        this._ws.onerror = this.wsError;
        this._ws.onclose = this.wsClose;
    },
    wsSend: function(data, callback) {
        // console.log('send', data);
        let that = ws;
        let data_copy = JSON.parse(JSON.stringify(data));
        if(!that._params[data_copy.api]) that._params[data_copy.api] = data_copy;
        if(that._ws && that._ws.readyState === that._ws.OPEN) {
            that._ws.send(JSON.stringify(that._params[data_copy.api]));
            if(data_copy.api && data_copy.api!== 'heartbeat') that._callbacks[data_copy.api] = callback;
        }
    },
    wsOpen: function() {
        // console.log('socketjs open');
        let that = ws;
        let _interval = 0;
        if(that._ws && that._ws.readyState === that._ws.OPEN) {//连接成功
            that.wsSend(that._connect_param);
            _interval && clearInterval(_interval);
            _interval = setInterval(() => {//成功之后开启心跳监测
                if(that._ws.readyState === that._ws.OPEN) {
                    that.wsSend(that._connect_param);
                }else{
                    clearInterval(_interval);
                }
            }, that._timeout);
        }
    },
    wsMsg: function(e) {
        let that = ws;
        if(that._ws && that._ws.readyState === that._ws.OPEN) {
            try {
                let data = JSON.parse(e.data);
                if(data.type === 'message') that.is_connected = true;
                else data && that._callbacks[data.type] && that._callbacks[data.type](data);

            } catch (error) {
                console.log(error);
            }
        }
    },
    wsError:function() {
        ws.initWs();
    },
    wsClose: function() {
        // ws.initWs();
    },
    handleWsClose() {
        ws._ws.close();
        ws._ws = null;
    }
};

export default ws;
